from django.shortcuts import render, HttpResponse, redirect
from django.template import RequestContext
from django.http import Http404
from django.contrib.auth.decorators import login_required
from page.utils import get_active_diagnostic_test
from engonline.models import UserAnswer

@login_required
def home(request):
	"""
	Returns the intro page if the user does not have a answer recorded for the current diagnostic test.
	Otherwise, returns a redirect to my progress.
	"""
	try:
		done_diagnostic = UserAnswer.objects.filter(user=request.user, test=get_active_diagnostic_test()).exists()
		if done_diagnostic:
			return redirect('page.views.my_progress')
	except Exception, e:
		raise e

	return render(request, 'home.html')

@login_required
def view_as(request):
	"""
	Sets the viewing_as_student session variable to true or false.
	Returns 404 if not POST and ajax.
	"""
	if request.method == 'POST' and request.is_ajax():
		try:
			view_as = request.POST['view-as']

			if view_as == 'student':
				request.session['viewing_as_student'] = True
			else:
				request.session['viewing_as_student'] = False

			return HttpResponse(status=200)
		except Exception, e:
			return HttpResponse(status=400)
	else:
		raise Http404